#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:通过某个字段将记录分组
问题: 你有一个字典或者实例的序列，然后你想根据某个特定的字段比如 date 来分组迭代访问。
提示 : 
"""
from operator import itemgetter
from itertools import groupby

rows = [
    {'address': '5412 N CLARK', 'date': '07/01/2012'},
    {'address': '5148 N CLARK', 'date': '07/04/2012'},
    {'address': '5800 E 58TH', 'date': '07/02/2012'},
    {'address': '2122 N CLARK', 'date': '07/03/2012'},
    {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
    {'address': '1060 W ADDISON', 'date': '07/02/2012'},
    {'address': '4801 N BROADWAY', 'date': '07/01/2012'},
    {'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]
print(f"{rows = }")

def recipe1():
    # 先排序
    rows.sort(key=itemgetter('date'))
    # 再分组
    for date, items in groupby(rows, key=itemgetter('date')):
        print(f"{date = }")
        for i in items:
            print(f"{' ', i = }")


def recipe2():
    """根据 date 字段将数据分组到一个大的数据结构中去，并且允许随机访问"""
    from collections import defaultdict
    rows_by_date = defaultdict(list)
    for row in rows:
        rows_by_date[row['date']].append(row)
    print(f"{rows_by_date = }")

    # 很轻松的就能对每个指定日期访问对应的记录
    for r in rows_by_date['07/01/2012']:
        print(f"{r = }")


def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()


if __name__ == '__main__':
    main()
